//
//  RouString.swift
//  ShangYouNews
//
//  Created by wangkun on 2017/5/21.
//  Copyright © 2017年 baymax. All rights reserved.
//

import UIKit

extension String {
    
    /// 字符串转Date
    ///
    /// - Parameter format: 格式
    /// - Returns: 转化后的Date
    public func toDate(format: String = "yyyy-MM-dd HH:mm:ss") -> Date {
        
        if isPurnFloat() {//全是数字
            let time = TimeInterval(self)
            let date = Date.init(timeIntervalSince1970: time!)
            return date
        }
        let dateFormate: DateFormatter = DateFormatter()
        dateFormate.dateFormat = format
        return dateFormate.date(from: self) ?? Date()
    }
    
    public func formatTime(_ inFormat: String = "yyyy-MM-dd HH:mm:ss", outFormat: String) -> String {
        let date = self.toDate(format: inFormat)
        return date.toString(format: outFormat)
    }
    
    /// 判断字符串是否为数字
    public func isPurnFloat() -> Bool {
        let scan: Scanner = Scanner(string: self)
        var val:Float = 0
        return scan.scanFloat(&val) && scan.isAtEnd
        
    }
    
    //时间格式转换
    public func timeFormatConversion(format: String = "yyyy-MM-dd HH:mm:ss") -> String {
        let date : Date = self.toDate(format: format)
        let currentDate: Date = Date.init(timeIntervalSinceNow: 0)
        let calendar: NSCalendar = NSCalendar.current as NSCalendar
        let dateComponents: DateComponents = calendar.components([.day,.hour,.minute,.minute], from: date, to:currentDate , options: .init(rawValue: 0))
        if dateComponents.day ?? 0 > 0{
            return date.toString(format: "MM-dd HH:mm")
        } else if dateComponents.hour ?? 0 > 0 {
            return "\(dateComponents.hour ?? 0)小时以前"
        } else if dateComponents.minute ?? 0 > 30 {
            return "\(dateComponents.minute ?? 0)分钟前"
        } else {
            return "刚刚"
        }
        
    }
    
    /// 获取字符串中指定字符之后的文本
    ///
    /// - Parameter string: 指定字符串
    /// - Returns: 符合要求的文本
    public func containsReplaceToEnd(_ string: String) -> String? {
        if self.contains(string) {
            var range = self.range(of: string)
            range = (range?.upperBound)! ..< self.endIndex
            let substr = self[range!]
            return String(substr) //self.substring(with: range!)
        }
        return nil
    }
    
    /// 获取字符串中指定字符之前的文本
    ///
    /// - Parameter string: 指定字符串
    /// - Returns: 符合要求的文本
    public func containsReplaceToStart(_ string: String) -> String? {
        if self.contains(string) {
            var range = self.range(of: string)
            range = self.startIndex ..< (range?.lowerBound)!
            let substr = self[..<(range?.lowerBound)!]
            return String(substr) //self.substring(with: range!)
        }
        return nil
    }
    
    /// 判断是否为全链接
    public func isFullLink() -> Bool {
        // 创建一个正则表达式对象
        do {
            let str = self.trimmingCharacters(in: .whitespaces)
            let dataDetector = try NSDataDetector(types:
                NSTextCheckingTypes(NSTextCheckingResult.CheckingType.link.rawValue))
            // 匹配字符串，返回结果集
            let res = dataDetector .matches(in: str, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, str.count))
            // 判断结果(完全匹配)
            if res.count == 1  && res[0].range.location == 0
                && res[0].range.length == str.count {
                return true
            }
        }
        catch {
            print(error)
        }
        return false
    }
    
    /// 获取全链接(String格式)、可以去除链接中的空格与特殊字符
    public mutating func getFullLink(_ host: String? = "") -> String {
        if self.count > 0 {
            self = self.trimmingCharacters(in: .whitespaces)
            self = self.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
            if !self.isFullLink() {
                if self.first() == "/" && host?.last() == "/" {
                    self.remove(at: self.startIndex)
                }
                self = (host ?? "") + self
            }
            return self
        }
        return ""
    }
    
    /// 获取全链接(URL格式)
    public mutating func getFullUrl(_ host: String? = "") -> URL? {
        return URL(string: self.getFullLink(host))
    }
    
    /// 第一个字符
    public mutating func first() -> String {
        if self.count > 0 {
            let index = self.startIndex
            return String(self[index])
        }
        return ""
    }
    
    /// 最后一个字符
    public func last() -> String {
        if self.count > 0 {
            let string = self
            let substr = string[string.index(before: string.endIndex)]
            return String(substr)
//            string = String(string.substring(from: string.index(before: string.endIndex)))
//            return string
        }
        return ""
    }
    
    public func toJSON() -> Any? {
        let data = self.data(using: String.Encoding.utf8)
        
        let json = try? JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String: Any]
        return json// as? T
    }
    
    /** 字符串长度*/
    public func length() -> Int{
        return count
    }
    
    /** 上游加密*/
    public mutating func shangyouSecurity() -> String {
        self = self.appending("3TrSW!WoYtEk$adB")
        return self.md5() ?? ""
    }
}
